package org.tao.lightningmq.common.remote;

import org.tao.lightningmq.common.tcp.TcpMsg;

import java.util.concurrent.*;

/**
 * @Author lht
 * @date 2025/1/8 - 17:36
 * @description:
 */
public class SyncFuture implements Future<TcpMsg> {

    private volatile boolean isDone;
    private volatile String msgId;
    private final BlockingDeque<TcpMsg> queue = new LinkedBlockingDeque<>(1);

    @Override
    public boolean cancel(boolean mayInterruptIfRunning) {
        return false;
    }

    @Override
    public boolean isCancelled() {
        return false;
    }

    @Override
    public boolean isDone() {
        return isDone;
    }

    @Override
    public TcpMsg get() throws InterruptedException, ExecutionException {
        TcpMsg res = queue.take();
        SyncFutureManager.remove(msgId);
        return res;
    }

    @Override
    public TcpMsg get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
        TcpMsg res = queue.poll(timeout, unit);
        SyncFutureManager.remove(msgId);
        return res;
    }

    public void setResp(TcpMsg resp) {
        this.isDone = true;
        try {
            this.queue.put(resp);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    public String getMsgId() {
        return msgId;
    }

    public void setMsgId(String msgId) {
        this.msgId = msgId;
    }
}
